<template>
  <div class="export-container">
    <div class="page-header">
      <h2>导出对账单</h2>
      <el-button @click="goBack">返回列表</el-button>
    </div>
    
    <el-card shadow="never">
      <div class="export-form">
        <h3>选择导出条件</h3>
        <el-form ref="formRef" :model="form" label-width="100px">
          <el-form-item label="时间范围" prop="date_range" required>
            <el-date-picker
              v-model="form.date_range"
              type="daterange"
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              value-format="YYYY-MM-DD"
              :disabled-date="disabledDate"
              style="width: 100%"
            />
          </el-form-item>
          
          <el-form-item label="支付渠道">
            <el-select v-model="form.channel" placeholder="请选择支付渠道" clearable style="width: 100%">
              <el-option v-for="item in channelOptions" :key="item.value" :label="item.label" :value="item.value" />
            </el-select>
          </el-form-item>
          
          <el-form-item label="导出格式">
            <el-radio-group v-model="form.format">
              <el-radio label="excel">Excel</el-radio>
              <el-radio label="csv">CSV</el-radio>
            </el-radio-group>
          </el-form-item>
          
          <el-form-item>
            <el-button type="primary" @click="handleExport" :loading="exporting">导出对账单</el-button>
          </el-form-item>
        </el-form>
      </div>
      
      <el-divider content-position="left">导出记录</el-divider>
      
      <el-table :data="exportRecords" style="width: 100%" v-loading="loading" border>
        <el-table-column prop="id" label="ID" width="80" />
        <el-table-column prop="file_name" label="文件名称" min-width="200" />
        <el-table-column prop="date_range" label="时间范围" width="200" />
        <el-table-column prop="channel" label="支付渠道" width="120">
          <template #default="scope">
            {{ getPaymentChannelText(scope.row.channel) || '全部' }}
          </template>
        </el-table-column>
        <el-table-column prop="format" label="文件格式" width="100">
          <template #default="scope">
            <el-tag>{{ scope.row.format.toUpperCase() }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="create_time" label="导出时间" width="180" />
        <el-table-column prop="status" label="状态" width="100">
          <template #default="scope">
            <el-tag :type="scope.row.status === 'completed' ? 'success' : (scope.row.status === 'processing' ? 'warning' : 'danger')">
              {{ getExportStatusText(scope.row.status) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="120" fixed="right">
          <template #default="scope">
            <el-button 
              v-if="scope.row.status === 'completed'" 
              type="primary" 
              size="small" 
              @click="handleDownload(scope.row)"
            >下载</el-button>
          </template>
        </el-table-column>
      </el-table>
      
      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :page-sizes="[10, 20, 50]"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>
  </div>
</template>

<script>
import { ref, reactive, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import request from '@/utils/request'

export default {
  name: 'PaymentExport',
  setup() {
    const router = useRouter()
    const formRef = ref(null)
    const loading = ref(false)
    const exporting = ref(false)
    const exportRecords = ref([])
    const total = ref(0)
    const currentPage = ref(1)
    const pageSize = ref(10)
    
    // 支付渠道选项
    const channelOptions = [
      { label: '微信小程序', value: 'wechat_mini' },
      { label: '微信JSAPI', value: 'wechat_jsapi' },
      { label: '微信H5', value: 'wechat_h5' },
      { label: '支付宝', value: 'alipay' },
      { label: '线下支付', value: 'offline' }
    ]
    
    // 表单数据
    const form = reactive({
      date_range: [],
      channel: '',
      format: 'excel'
    })
    
    // 禁用日期（不能选择未来日期）
    const disabledDate = (time) => {
      return time.getTime() > Date.now()
    }
    
    // 获取导出记录
    const fetchExportRecords = async () => {
      loading.value = true
      try {
        const params = {
          page: currentPage.value,
          page_size: pageSize.value
        }
        
        const response = await request.get('/v1/admin/payments/export-records', { params })
        exportRecords.value = response.data.items || []
        total.value = response.data.total || 0
      } catch (error) {
        console.error('获取导出记录失败', error)
        ElMessage.error('获取导出记录失败')
      } finally {
        loading.value = false
      }
    }
    
    // 页码变化
    const handleCurrentChange = (page) => {
      currentPage.value = page
      fetchExportRecords()
    }
    
    // 每页条数变化
    const handleSizeChange = (size) => {
      pageSize.value = size
      fetchExportRecords()
    }
    
    // 导出对账单
    const handleExport = async () => {
      if (!form.date_range || form.date_range.length !== 2) {
        ElMessage.warning('请选择时间范围')
        return
      }
      
      exporting.value = true
      try {
        const params = {
          start_date: form.date_range[0],
          end_date: form.date_range[1],
          channel: form.channel,
          format: form.format
        }
        
        await request.post('/v1/admin/payments/export', params)
        
        ElMessage.success('导出任务已提交，请稍后在导出记录中下载')
        fetchExportRecords()
      } catch (error) {
        console.error('导出对账单失败', error)
        ElMessage.error('导出对账单失败: ' + (error.response?.data?.message || '未知错误'))
      } finally {
        exporting.value = false
      }
    }
    
    // 下载导出文件
    const handleDownload = (record) => {
      window.open(`/v1/admin/payments/download/${record.id}`)
    }
    
    // 返回列表页
    const goBack = () => {
      router.push('/payment/list')
    }
    
    // 获取支付渠道文本
    const getPaymentChannelText = (channel) => {
      if (!channel) return '全部'
      
      const channelMap = {
        'wechat_mini': '微信小程序',
        'wechat_jsapi': '微信JSAPI',
        'wechat_h5': '微信H5',
        'alipay': '支付宝',
        'offline': '线下支付'
      }
      return channelMap[channel] || channel
    }
    
    // 获取导出状态文本
    const getExportStatusText = (status) => {
      const statusMap = {
        'pending': '等待中',
        'processing': '处理中',
        'completed': '已完成',
        'failed': '失败'
      }
      return statusMap[status] || status
    }
    
    onMounted(() => {
      fetchExportRecords()
    })
    
    return {
      formRef,
      form,
      loading,
      exporting,
      exportRecords,
      channelOptions,
      currentPage,
      pageSize,
      total,
      disabledDate,
      handleCurrentChange,
      handleSizeChange,
      handleExport,
      handleDownload,
      goBack,
      getPaymentChannelText,
      getExportStatusText
    }
  }
}
</script>

<style lang="scss" scoped>
.export-container {
  .page-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 20px;
    
    h2 {
      margin: 0;
      font-size: 20px;
    }
  }
  
  .export-form {
    max-width: 600px;
    margin: 0 auto 30px;
    
    h3 {
      margin-top: 0;
      margin-bottom: 20px;
      font-size: 18px;
      text-align: center;
    }
  }
  
  .pagination-container {
    margin-top: 20px;
    display: flex;
    justify-content: flex-end;
  }
}
</style> 